
package tv.youxing.android.custom;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.http.VolleyError;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import tv.youxing.android.R;
import tv.youxing.android.adapter.HotWordAdapter;
import tv.youxing.android.entity.SearchResultModel;
import tv.youxing.android.entity.VideoPlayerPostModel;
import tv.youxing.android.ui.SubscribeDeteilsActivity;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.RecordSQLiteOpenHelper;
import tv.youxing.android.utils.StaticClass;


/**
 * Created by Carson_Ho on 16/11/15.
 */
public class Search_View extends LinearLayout {

    private Context context;
    private Activity mActivity;
//    private List<TaskModel> mList = new ArrayList<TaskModel>();

    /*UI组件*/
    private TextView tv_clear;
    private EditText et_search;
    private TextView tv_tip;
    private ImageView iv_search;
    private ImageView iv_back_form_search;
    /*列表及其适配器*/
    private SearchListView listView;
    private BaseAdapter adapter;

    /*数据库变量*/
    private RecordSQLiteOpenHelper helper;
    private SQLiteDatabase db;

    private LinearLayout layout_hotwords;
    private GridView gridView;
    private HotWordAdapter hotWordAdapter;
    private List<String> hotWordList = new ArrayList<>();
    private CustomListView customListView;


    SearchResultModel mAlldata;

    /*三个构造函数*/
    //在构造函数里直接对搜索框进行初始化 - init()
    public Search_View(Context context) {
        super(context);
        this.context = context;
        mActivity = (Activity) context;
        init();
    }

    public Search_View(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        mActivity = (Activity) context;
        init();
    }

    public Search_View(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        mActivity = (Activity) context;
        init();
    }


    /*初始化搜索框*/
    private void init() {


        getKeywordsRequest();

        //初始化UI组件
        initView();


        //实例化数据库SQLiteOpenHelper子类对象
        helper = new RecordSQLiteOpenHelper(context);


        // 第一次进入时查询所有的历史记录
        queryData("");


        //"清空搜索历史"按钮
        tv_clear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                //清空数据库
                deleteData();
                queryData("");
            }
        });

        //搜索框的文本变化实时监听
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                L.i("beforeTextChanged");

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                L.i("onTextChanged");

            }

            //输入后调用该方法
            @Override
            public void afterTextChanged(Editable s) {
//                L.i("输入后调用该方法");
//                customListView.setVisibility(View.GONE);
//                listView.setVisibility(View.VISIBLE);
//
//                if (s.toString().trim().length() == 0) {
//                    //若搜索框为空,则模糊搜索空字符,即显示所有的搜索历史
//                    tv_tip.setText("搜索历史");
//                    layout_hotwords.setVisibility(View.VISIBLE);
//
//                } else {
//                    tv_tip.setText("搜索结果");
//                    layout_hotwords.setVisibility(View.GONE);
//                    requestTaskByKeywords(et_search.getText().toString());
//                }
//
//                //每次输入后都查询数据库并显示
//                //根据输入的值去模糊查询数据库中有没有数据
//                String tempName = et_search.getText().toString();
//                queryData(tempName);

            }
        });


        // 搜索框的键盘搜索键
        // 点击回调
        et_search.setOnKeyListener(new OnKeyListener() {// 输入完后按键盘上的搜索键


            // 修改回车键功能
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                L.i("搜索框的键盘搜索键");
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 隐藏键盘，这里getCurrentFocus()需要传入Activity对象，如果实际不需要的话就不用隐藏键盘了，免得传入Activity对象，这里就先不实现了
//                    ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
//                            getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    boolean hasData = hasData(et_search.getText().toString().trim());
                    if (!hasData) {
                        if (et_search.getText().toString().trim().length() > 0) {
                            insertData(et_search.getText().toString().trim());
                            queryData("");
                        }
                    }
                    //根据输入的内容模糊查询商品，并跳转到另一个界面，这个需要根据需求实现
                    Toast.makeText(context, "点击搜索", Toast.LENGTH_SHORT).show();

                }
                return false;
            }
        });

        //搜索热词关键字点击
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                L.i("onItemClick  " + position);
                String searchText = hotWordList.get(position);
                if (searchText.length() > 0) {
                    requestTaskByKeywords(searchText);
                }
            }
        });

        //搜索结果任务点击
        customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                L.i("onItemClickcustomListView:  " + position);
//                TaskModel taskModel = mList.get(position);
//                Intent intent = new Intent(context, TaskDetailActivity.class);
//                intent.putExtra("taskID", String.valueOf(taskModel.getId()));
//                context.startActivity(intent);

                SearchResultModel.ResultBean.DataBean m = mAlldata.getResult().getData().get(position);




                VideoPlayerPostModel model = new VideoPlayerPostModel();
                model.setMultimedia_id(m.getMultimedia_id());
                model.setTitle(m.getTitle());
                model.setIntro(m.getIntro());
                model.setCover(m.getCover());
                model.setDuration(m.getDuration());
                model.setPublish_at(m.getPublish_at());
                model.setPlay_url(m.getPlay_url());
                model.setType(m.getType());
                model.setPlay_count(m.getPlay_count());
                model.setComment_count(m.getComment_count());
                model.setLike_count(m.getLike_count());
                model.setCollection_count(m.getCollection_count());
                model.setStatus(m.getStatus());
                model.setCreated_at(m.getCreated_at());
                model.setUpdated_at(m.getUpdated_at());
                model.setAlbum_name(m.getAlbum().getName());
                model.setIs_collectied(m.getIs_collectied());
                model.setIs_like(m.getIs_like());
                model.setVideo_share_url(m.getVideo_share_url());
                VideoPlayerPostModel.AlbumBean albumBean = new VideoPlayerPostModel.AlbumBean();
                albumBean.setAlbum_id(m.getAlbum().getAlbum_id());
                albumBean.setName(m.getAlbum().getName());
                albumBean.setCover(m.getAlbum().getCover());
                albumBean.setIs_order(m.getAlbum().getIs_order());
                model.setAlbum(albumBean);

                Intent intent = new Intent(getContext(), SubscribeDeteilsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("data",model);
                intent.putExtras(bundle);
                getContext().startActivity(intent);
            }
        });

        //列表监听
        //即当用户点击搜索历史里的字段后,会直接将结果当作搜索字段进行搜索
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                L.i("即当用户点击搜索历史里的字段后,会直接将结果当作搜索字段进行搜索");
                //获取到用户点击列表里的文字,并自动填充到搜索框内
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                et_search.setText(name);
                requestTaskByKeywords(name);
//                Toast.makeText(context, name + "---哒哒哒", Toast.LENGTH_SHORT).show();

            }
        });

//        // 插入数据，便于测试，否则第一次进入没有数据怎么测试呀？
//        Date date = new Date();
//        long time = date.getTime();
//        insertData("Leo" + time);

        //点击搜索按钮后的事件
        iv_search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                L.i("点击搜索按钮后的事件");

                //检测数据库是否有该条数据
                boolean hasData = hasData(et_search.getText().toString().trim());
                if (!hasData) {
                    //搜索后显示数据库里所有搜索历史是为了测试
                    if (et_search.getText().toString().trim().length() > 0) {
                        insertData(et_search.getText().toString().trim());
                        queryData("");

                    }
                    System.out.println("数据库无");
                } else {

                    System.out.println("数据库有");

                }
                //根据输入的内容模糊查询商品，并跳转到另一个界面，这个根据需求实现
//                Toast.makeText(context, "clicked!", Toast.LENGTH_SHORT).show();


                String searchText = et_search.getText().toString().trim();
                if (searchText.length() > 0) {
                    requestTaskByKeywords(searchText);
                }

            }
        });


    }

    //URL中文转义
    public static String encodeUrl(String url) {
        return Uri.encode(url, "-![.:/,%?&=]");
    }

    private void requestTaskByKeywords(String searchText) {
        listView.setVisibility(View.GONE);
        customListView.setVisibility(View.VISIBLE);


        //post请求简洁版实现
        HttpParams params = new HttpParams();
        params.put("keyword", searchText);

        RxVolley.post(StaticClass.keywordsTaskURL, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mAlldata = GsonUtils.GsonToBean(t, SearchResultModel.class);

                if (mAlldata.getCode() == 200) {

                    if (mAlldata.getResult().getData().size() > 0) {
                        customListView.setAdapter(new SearchResultAdapter(getContext(), mAlldata.getResult().getData()));
                    } else {
                        CustomToast.INSTANCE.showToast("查无此数据");
                    }

                }
            }
        });

    }


    private void getKeywordsRequest() {

        if (hotWordList != null && hotWordList.size() > 0) {

        } else {
            //搜索热词
            RxVolley.get(StaticClass.getHotWordsURL, new HttpCallback() {
                @Override
                public void onSuccess(String t) {
                    super.onSuccess(t);
                    L.i("请求到的数据getHotWordsURL_result:     " + t);
                    JSONArray jsonArray = null;
                    try {
                        jsonArray = new JSONObject(t).getJSONArray("data");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String hotword = jsonObject.getString("words");
                            hotWordList.add(hotword);
                            hotWordAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(VolleyError error) {
                    super.onFailure(error);
                    //UtilTools.getVolleyError(context, error);
                }
            });
        }

    }


    /**
     * 封装的函数
     */

    /*初始化组件*/
    private void initView() {
        LayoutInflater.from(context).inflate(R.layout.layout_search, this);
        et_search = (EditText) findViewById(R.id.et_search);
        tv_clear = (TextView) findViewById(R.id.tv_clear);
        tv_tip = (TextView) findViewById(R.id.tv_tip);
        listView = (SearchListView) findViewById(R.id.listView);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        iv_back_form_search = (ImageView) findViewById(R.id.iv_back_form_search);
        iv_back_form_search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                context.startActivity(new Intent(context, MainActivity.class));
                mActivity.finish();
            }
        });

        layout_hotwords = (LinearLayout) findViewById(R.id.layout_hotwords);
        gridView = (GridView) findViewById(R.id.noScrollgridview);
        hotWordAdapter = new HotWordAdapter(context, hotWordList);
        gridView.setAdapter(hotWordAdapter);

        customListView = (CustomListView) findViewById(R.id.customListView);

    }

    /*插入数据*/
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }

    /*模糊查询数据 并显示在ListView列表上*/
    private void queryData(String tempName) {

        //模糊搜索
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
        // 创建adapter适配器对象,装入模糊搜索的结果
        adapter = new SimpleCursorAdapter(context, R.layout.search_lishi_layout_item, cursor, new String[]{"name"},
                new int[]{android.R.id.text1}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 设置适配器
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    /*检查数据库中是否已经有该条记录*/
    private boolean hasData(String tempName) {
        //从Record这个表里找到name=tempName的id
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /*清空数据*/
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }


    class SearchResultAdapter extends BaseAdapter {

        private Context context;
        private List<SearchResultModel.ResultBean.DataBean> videoModelList = new ArrayList<>();
        private LayoutInflater layoutInflater;

        public SearchResultAdapter(Context context, List<SearchResultModel.ResultBean.DataBean> videoModelList) {
            this.context = context;
            this.videoModelList = videoModelList;
            layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return videoModelList.size() > 6 ? 6 : videoModelList.size();
        }

        @Override
        public Object getItem(int position) {
            return videoModelList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (viewHolder == null) {
                viewHolder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.layout_item_search_result, null);
                viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.head);
                viewHolder.tvName = (TextView) convertView.findViewById(R.id.title);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }


            ImageLoader.getInstance().displayImage(videoModelList.get(position).getCover(),viewHolder.ivIcon);
            viewHolder.tvName.setText(videoModelList.get(position).getTitle());

            return convertView;
        }


        class ViewHolder {
            private ImageView ivIcon;
            private TextView tvName;
        }
    }
}
